<template> 
<div>
  <div class="bgfff mtrbl20 ptrbl20 nopb20">
  <el-row :gutter="20">
    <!--用户数据-->
    <el-col :span="24" :xs="24">
    <el-form :model="queryParams1" ref="queryForm" :inline="true">
    <el-form-item  prop="cascade">
      <el-cascader style="width:300px"
      v-model="queryParams1.cascade"
      :options="companyAdminCascadeOptions"
      :props="{ expandTrigger: 'hover' }"
      placeholder="请选择省份-管理企业-客户企业"
      clearable>
      <template slot-scope="{ node, data }">
        <span>{{ data.label }}</span>
        <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
      </template>
      </el-cascader>
    </el-form-item>

    <el-form-item prop="months">
      <el-date-picker
      v-model="queryParams1.months"
      type="monthrange"
      value-format="yyyy-MM"
      align="left"
      unlink-panels
      range-separator="至"
      start-placeholder="开始月份"
      end-placeholder="结束月份" 
      :picker-options="pickerOptions">
    </el-date-picker>
    </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-finished" size="medium" @click="handleQuery" v-hasPermi="['taxmsg:predeclare:verify']">预生成</el-button>
        <el-button icon="el-icon-refresh" size="medium" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </el-col>
  </el-row>
</div> 
   <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-table v-loading="loading" :data="predeclareList">
          <el-table-column fixed label="序号" prop="" width="55" align="center">
            <template slot-scope="scope">
              <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
            </template>
          </el-table-column>
          <el-table-column label="管理企业" align="left" key="companyAdminNames" prop="companyAdminNames" :show-overflow-tooltip="true"/>
          <el-table-column label="实际管理企业" align="left" key="actualCompanyAdminNames" prop="actualCompanyAdminNames" :show-overflow-tooltip="true"/>
          <el-table-column label="客户企业" align="left" key="companyNames" prop="companyNames" :show-overflow-tooltip="true"/>
          <el-table-column label="实际客户企业" align="left" key="actualCompanyNames" prop="actualCompanyNames" :show-overflow-tooltip="true"/>
          <el-table-column label="完税省份" align="left" key="provinceName" prop="provinceName" />
          <el-table-column label="申报日期" align="left" key="months" prop="months" :show-overflow-tooltip="true"/>
          <el-table-column label="实际申报日期" align="left" key="actualMonths" prop="actualMonths" :show-overflow-tooltip="true"/>
          <el-table-column label="总人数" align="left" key="totalPeople" prop="totalPeople" />
          <el-table-column label="总金额" align="left" key="totalMoney" prop="totalMoney" />
          <el-table-column label="流程状态" align="left" key="processStatus.name" prop="processStatus.name" />
          <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="150">
            <template slot-scope="scope">
              <!-- <el-button size="small" type="text" icon="el-icon-view" @click="handleView(scope.row)" :disabled="scope.row.processStatus.code =='2' || scope.row.processStatus.code =='0'">详情</el-button>
              <el-button size="small" type="text" icon="el-icon-caret-right" @click="handleBuild(scope.row)" :disabled="scope.row.processStatus.code =='2' || scope.row.processStatus.code =='0'">确认生成</el-button>
              <el-button size="small" type="text" icon="el-icon-download" @click="handleExport(scope.row)" :disabled="scope.row.processStatus.code =='2' || scope.row.processStatus.code =='0'">导出数据</el-button>
              <el-button size="small" type="text" icon="el-icon-delete" @click="handleDiscard(scope.row)" :disabled="scope.row.processStatus.code =='2' || scope.row.processStatus.code =='0'">数据作废</el-button> -->
              <el-dropdown size="mini" split-button type="primary" @click="handleView(scope.row)" placement="bottom-start" trigger="click">
                详 情
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item icon="el-icon-caret-right" @click.native="handleBuild(scope.row)" :disabled="scope.row.processStatus.code =='2' || scope.row.processStatus.code =='0'" v-hasPermi="['taxmsg:predeclare:build']">确认生成</el-dropdown-item>
                  <el-dropdown-item icon="el-icon-download" @click.native="handleExport(scope.row)" :disabled="scope.row.processStatus.code =='2' || scope.row.processStatus.code =='0'" v-hasPermi="['taxmsg:predeclare:download']">导出数据</el-dropdown-item>
                  <el-dropdown-item icon="el-icon-delete" @click.native="handleDiscard(scope.row)" :disabled="scope.row.processStatus.code =='2' || scope.row.processStatus.code =='0'" v-hasPermi="['taxmsg:predeclare:discard']">数据作废</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 创建预申报批次数据提示对话框 -->
    <el-dialog title="校验不通过,数据存在冲突是否继续？" :visible.sync="openDeclareVerify" width="800px" append-to-body>
      <el-table v-loading="loading" :data="declareVerifyList">
        <el-table-column label="存在冲突的id" align="left" key="collectionInfoId" prop="collectionInfoId"/>
        <el-table-column label="存在冲突的姓名" align="left" key="realName" prop="realName"/>
        <el-table-column label="存在冲突的身份证号" align="left" key="idNumber" prop="idNumber" />
      </el-table>  
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定构造</el-button>
        <el-button @click="cancelDeclareVerify">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</div>
</template>

<script>
import { predeclareList, predeclareDiscard, predeclareDataDownload, predeclareBuild, declareVerify, declareBuild } from "@/api/taxmsg/predeclare";
export default {
  name: "Predeclare",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 用户表格数据
      predeclareList: null,
      declareVerifyList: null,
      props: { multiple: true },
      // 构造预申报数据级联条件
      companyAdminCascadeOptions: [],
      // 是否显示弹出层
      open: false,
      openDeclareVerify: false,
      queryParams1: {
      },
      queryParams2: {
        provinceCode:null,
        companyAdminIds:null,
        companyIds: null,
        months:null,
        years:null
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20
      },
      pickerOptions: {
          shortcuts: [{
            text: '本月',
            onClick(picker) {
              picker.$emit('pick', [new Date(), new Date()]);
            }
          }, {
            text: '今年至今',
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().getFullYear(), 0);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近六个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit('pick', [start, end]);
            }
          }]
        }
     
    };
  },
  created() {
    this.getList();
    this.getCompanyAdminCascade().then(response => {
        this.companyAdminCascadeOptions = response.data;
      }
    ); 
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      predeclareList(this.queryParams).then(response => {
          this.predeclareList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    /** 详情按钮操作 */
    handleView(row) {
      const id = row.id || this.ids[0];
      this.$router.push("/predeclare/details/" + id);
    },
    /** 搜索按钮操作 */
    handleQuery() {
        if (this.queryParams1.cascade && this.queryParams1.months) {
          if(this.queryParams1.cascade.map(item => item[0]).distinct().length==1){
            const provinceCode =  this.queryParams1.cascade.map(item => item[0])[0];
            const companyAdminIds =  this.queryParams1.cascade.map(item => item[1]).distinct();
            const companyIds =  this.queryParams1.cascade.map(item => item[2]).distinct();

            //alert(this.queryParams1.months.map(item => item)[0])
            //alert(this.queryParams1.months.map(item => item)[1])
            const getMonthBetween = this.getMonthBetween(this.queryParams1.months.map(item => item)[0],this.queryParams1.months.map(item => item)[1]);
            //console.log(getMonthBetween.map(item => item.replace(/\-/g, "")));
            this.queryParams2.provinceCode = provinceCode;
            this.queryParams2.companyAdminIds = companyAdminIds;
            this.queryParams2.companyIds = companyIds;
            //this.queryParams2.months  = this.queryParams1.months;
            //console.log(this.queryParams1.months.map(item => item)[0])
            //console.log(this.queryParams1.months.map(item => item)[1])
            this.queryParams2.months = getMonthBetween.map(item => item.replace(/\-/g, ""));

            this.queryParams2.years = this.queryParams1.months.map(item => item.slice(0,4)).distinct();

            // const getYearArr = this.getYearArr(this.queryParams1.months.map(item => item.slice(0,4))[0],this.queryParams1.months.map(item => item.slice(0,4))[1]);
            // console.log(getYearArr);
            // this.queryParams2.years = getYearArr.map(item => item.replace(/'/g, '"'));
            declareVerify(this.queryParams2).then(response => {
                  if(response.code === 1001){
                    this.openDeclareVerify = true;
                    this.declareVerifyList = response.data;
                  }else{
                    this.getDeclareBuild();
                  }
            }).catch(()=>{});;
          }else{
            this.$message({
              showClose: true,
              message: '不能跨省选择',
              type: 'error'
            });
          }
        }else{
          this.$message({
            showClose: true,
            message: '请选择预申报数据级联条件和完税时间',
            type: 'error'
           });
        }
    },
    // getMonthBetween(start,end){
    //   var result = [];
    //   var s = start.split("-");  
    //   var e = end.split("-");  
    //   var min = new Date();  
    //   var max = new Date();  
    //   min.setFullYear(s[0],s[1]);  
    //   max.setFullYear(e[0],e[1]);  
    //     //console.log(e[0]+"---- "+e[1]);
    //   var curr = min;  
    //   while(curr <= max){  
    //       var month = curr.getMonth();  
    //       //month=month==0?12:month;
    //       //console.log(month);
    //       var str=new String(curr.getFullYear())+(this.getzf(month));
    //       var s=new String(curr.getFullYear())+"0";
    //       if(str==s){
    //         str=new String(curr.getFullYear())+"12";
    //       }
    //       result.push(str);  
    //       curr.setMonth(month+1);
    //   }  
    //   return result;  
    // },
    getMonthBetween (start, end) {
      var result = [start];
      var starts = start.split('-');
      var ends = end.split('-');
      var staYear = parseInt(starts[0]);
      var staMon = parseInt(starts[1]);
      var endYear = parseInt(ends[0]);
      var endMon = parseInt(ends[1]);
      while (staYear <= endYear) {
        if (staYear === endYear) {
          while (staMon < endMon) {
            staMon++;
            result.push(staYear + '-' + this.getzf(staMon));
          }
          staYear++;
        } else {
          staMon++;
          if (staMon > 12) {
            staMon = 1;
            staYear++;
          }
          result.push(staYear + '-' + this.getzf(staMon));
        }
      }
      return result;
    },
    getzf(num){
        if(num > 0 && num < 10){
            num = '0'+num;  
        }
        return num || 0;
    },
    /*
    startYear 开始年份 参数为空时为当前年份前5年
    endYear 结束年份 参数为空时为当前年份
    */
    getYearArr(startYear,endYear){
        var yearArr=[],
            prDate = new Date(),
            presentYear = prDate.getFullYear();//当前年份
        if ( !endYear ) { //为空为当前年份
            endYear = presentYear;
    　　}
    　　if ( !startYear ) { //为空为当前年前5年
    　　　　startYear = presentYear-5;
    　　}
    　　for ( var i = startYear; i <= endYear; i++) {
    　　　　yearArr.push(i);
    　　}
    　　return yearArr;

    },
    getDeclareBuild() {
      //this.msgSuccess("执行构造");
      //this.openDeclareVerify = false;
      this.loading = true;
      declareBuild(this.queryParams2).then(response => {
          this.msgSuccess("预生成完税申报成功");
          this.openDeclareVerify = false;
          this.loading = false;
          this.getList();
      }).catch(()=>{this.loading = false;});
    },
    submitForm() {
      this.getDeclareBuild();
    },
    cancelDeclareVerify() {
      this.openDeclareVerify = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      //this.dateRange = [];
      this.resetForm("queryForm");
      //this.handleQuery();
      delete this.queryParams1.cascade
      delete this.queryParams1.months
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    // 确认作废
    handleDiscard(row) {
      const id = row.id || this.ids;
      this.$confirm('是否确认数据作废编号为"' + id + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return predeclareDiscard(id);
        }).then(response => {
          this.getList();
          this.msgSuccess(response.msg);
        }).catch(()=>{})
    },
     // 确认生成
     handleBuild(row) {
      const id = row.id || this.ids;
      this.$confirm('是否确认生成编号为"' + id + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return predeclareBuild(id);
        }).then(response => {
          this.getList();
          this.msgSuccess(response.msg);
        }).catch(()=>{})
    },
    /** 导出按钮操作 */
    handleExport(row) {
      const batchId = row.id || this.ids;
      this.$confirm('是否确认导出编号为"' + batchId + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return predeclareDataDownload({batchId});
        }).then(response => {
          //this.download(response.msg);
          var list_name = "预申报数据";
          this.export_excel_file(response, list_name);
        }).catch(()=>{})
    }
  }
};
</script>
<style scoped lang="scss">
</style>